package com.googlecode.jwsm;

import java.io.*;
import java.net.URLDecoder;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jcommon.util.*;

/**
 * Servlet implementation class for Servlet: ServiceRequest
 */
public class ServiceRequest extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}  	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Thread.currentThread().setName("ServiceRequest");
		String query = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("ServiceRequest/") + "ServiceRequest/".length());
		query = URLDecoder.decode(query, "UTF-8");
		String method = null;
		if (query.indexOf('/') > -1) {
			String[] split = query.split("/");
			query = split[0];
			if (split.length > 1) {
				method = split[1];
			}
		}
		
		Service service = ServiceManager.getInstance().getService(query);
		if (service != null) {
			Thread.currentThread().setName(service.getName());
			if (service.isStarted()) {
				if ((request.getQueryString() != null) && (request.getQueryString().equalsIgnoreCase("wsdl")) && (service.isInterceptWSDL())) {
					// WSDL requested
					response.setContentType("text/xml");
					InputStream in = getClass().getClassLoader().getResourceAsStream("resource/jwsm.wsdl");
					String wsdl = StringUtilities.toString(in);
					in.close();
					wsdl = StringUtilities.replaceAll(wsdl, "%%SERVICE_NAME%%", service.getName());
					wsdl = StringUtilities.replaceAll(wsdl, "%%SERVICE_URL%%", request.getRequestURL().toString());
					PrintWriter writer = response.getWriter();
					writer.write(wsdl);
					writer.flush();
					writer.close();
				} else {
					// Service request
					service.request(method, request, response);
				}
			} else {
				// The service is not started
				try {
					Service.writeSOAPFault(service, new ServletException("Service is stopped: " + query), response.getWriter());
				} catch(Throwable t) {
					t.printStackTrace();
				}
			}
		} else {
			// The service cannot be found
			try {
				Service.writeSOAPFault(null, new ServletException("Unable to find the service: " + query), response.getWriter());
			} catch(Throwable t) {
				t.printStackTrace();
			}
		}
	}
}